/**
 * 查询页自动创建类
 * @author guoguifang
 */
class SearchPage {
    constructor(stars, node, options) {
        this.stars = stars;
        this.node = node;
        this.modalId = options.modalId;
        this.url = options.url;
        this.isDataTable = options.dataTable === undefined ? true : options.dataTable;
        this.isCheck = options.isCheck === undefined ? true : options.isCheck;
        this.autoRefresh = options.autoRefresh || false;
        this.singleRefresh = options.singleRefresh || false;
        this.columns = options.columns || [];
        this.batchBtns = options.batchBtns || [];
        this.rightBtns = options.rightBtns || [];
        this.header = options.header;
        this.primaryKey = options.primaryKey;
        this.showCode = options.showCode;
        this.delete = options.delete || {};
        this.delete.conditionCode = this.delete.conditionCode || this.primaryKey;
        this.delete.showCode = this.delete.showCode || this.showCode;
        this.confirmTitleReplace = options.confirmTitleReplace;
        for (let key in options) {
            if (options.hasOwnProperty(key)) {
                if (typeof options[key] === 'function') {
                    this[key] = options[key];
                }
            }
        }
        this.init();
    }

    init() {
        this.widget = $('<div class="widget has-shadow"></div>');
        this.widgetBody = $('<div class="widget-body"></div>');
        this.table = $('<table class="table dataTable table-hover mb-0"></table>');
        this.thead = $('<thead></thead>');
        this.tbody = $('<tbody></tbody>');
        this.contentHeaderBtnCount = 0;
        this.checkedRows = [];
        this.node.html($('<div class="col-xl-12"></div>').append(this.widget));
        this.create();
    }

    create() {
        this.createContentHeader();
        this.createContentBody();
    }

    createContentHeader() {
        this.header && this.widget.append($('<div class="widget-header bordered no-actions d-flex align-items-center"></div>').append(this.header));
        if (this.isCheck || this.singleRefresh || this.autoRefresh || this.batchBtns.length > 0 || this.rightBtns.length > 0) {
            this.contentHeader = $('<div class="btn-header" style="padding:1.78rem 1.78rem 0 1.78rem"></div>').hide();
            this.widget.append(this.contentHeader);
            let that = this;
            if (this.autoRefresh) {
                this.autoRefreshBtnContainer = $('<span></span>');
                this.autoRefreshBtnContainer.append($('<button class="btn btn-gradient-04-left min-width-100" type="button"><span class="translate" translateFor="btn.openAutoRefresh"></span></button>').on('click', function () {
                        let $this = $(this);
                        let selectedBtn = $this.next();
                        let intervalBtn = selectedBtn.next();
                        that.createSearchTable(true, intervalBtn.find('.autoRefreshInterval').text() * 1000, false);
                        intervalBtn.addClass('selected');
                        $this.hide();
                        selectedBtn.show();
                    }))
                    .append($('<button class="btn btn-gradient-04-left min-width-100 selected" type="button"><span class="translate" translateFor="btn.closeAutoRefresh"></span></button>').on('click', function () {
                        let $this = $(this);
                        let unselectedBtn = $this.prev();
                        let intervalBtn = $this.next();
                        that.modalId ? clearModalTimeout(that.modalId) : clearPageTimeout();
                        that.refreshInterval = false;
                        intervalBtn.removeClass('selected');
                        $this.hide();
                        unselectedBtn.show();
                    }).hide())
                    .append($('<button class="btn btn-gradient-04-right min-width-50" type="button"><span class="autoRefreshInterval">3</span><span class="translate unit" translateFor="timeUnit.second"></span></button>').on('click', function () {
                        let $this = $(this);
                        if ($this.data('btnSelected')) {
                            hidePopoverByNode($this);
                            return;
                        }
                        let slider = createSlider({
                            min: 1,
                            max: 10,
                            defaultValue: $this.find('.autoRefreshInterval').text(),
                            unit: $this.find('.unit').text(),
                            background: 'linear-gradient(to right,#54e38e 0%,#41c7af 50%,#54e38e 100%)'
                        });
                        showPopover($this, {
                            direction: 'top',
                            bodyStyle: 'width:17.85rem;height:3.58rem;margin:0 0.43rem 1.07rem;',
                            bodyContent: slider,
                            animate: 'slide',
                            animateTime: 300,
                            leftOffset: '-0.285rem',
                            scrollLock: true,
                            hideFun(){
                                $this.data('btnSelected', false);
                                let sliderValue = getSliderValue(slider);
                                getSliderValue(slider) && $this.find('.autoRefreshInterval').text(sliderValue);
                                if ($this.hasClass('selected')) {
                                    that.modalId ? clearModalTimeout(that.modalId) : clearPageTimeout();
                                    that.createSearchTable(true, sliderValue * 1000, false);
                                }
                            }
                        });
                        $this.data('btnSelected', true);
                    }));
                this.contentHeader.append(this.autoRefreshBtnContainer);
                this.contentHeaderBtnCount++;
            }
            if (this.batchBtns.length > 0) {
                this.batchBtnContainer = $('<span></span>').hide();
                this.autoRefreshBtnContainer && this.batchBtnContainer.addClass('ml-3');
                for (let i = 0, l = this.batchBtns.length; i < l; i++) {
                    let c = this.batchBtns[i];
                    this.batchBtnContainer.append($('<button class="btn" type="button"><span class="translate" translateFor="' + this.getValue(c.translateFor) + '"></span></button>').on('click', () => {
                        if (c.fun) {
                            c.arg ? c.fun.call(this, c.arg) : c.fun.call(this);
                        } else {
                            let fun = this[c.action];
                            if (typeof fun === 'function') {
                                c.arg ? fun.call(this, c.arg) : fun.call(this);
                            }
                        }
                    }).addClass(l == 1 ? 'btn-gradient-04 min-width-150' : i == 0 ? 'btn-gradient-04-left min-width-100' : i == l - 1 ? 'btn-gradient-04-right min-width-100' : 'btn-gradient-04-center min-width-100'));
                }
                this.contentHeader.append(this.batchBtnContainer);
            }
            if (this.isCheck || this.singleRefresh || this.rightBtns.length > 0) {
                let rightBtns = $('<div style="float:right;margin-right:.15rem"></div>');
                let count = 0;
                if (this.singleRefresh) {
                    rightBtns.append($('<div class="iconBtn translate float-right" translateFor="text.singleRefresh" translateTo="popoverTitle" ><i class="ti ti-reload"></i></div>').on('click', () => this.createSearchTable(true, false, true)));
                    count++;
                    this.contentHeaderBtnCount++;
                }
                if (this.rightBtns.length > 0) {
                    for (let j = 0, k = this.rightBtns.length; j < k; j++) {
                        let c = this.rightBtns[j];
                        rightBtns.append($('<div class="iconBtn translate float-right" translateFor="' + this.getValue(c.translateFor) + '" translateTo="popoverTitle" ><i class="' + this.getValue(c.icon) + '"></i></div>').on('click', () => {
                            if (c.fun) {
                                c.arg ? c.fun.call(this, c.arg) : c.fun.call(this);
                            } else {
                                let fun = this[c.action];
                                if (typeof fun === 'function') {
                                    c.arg ? fun.call(this, c.arg) : fun.call(this);
                                }
                            }

                        }).addClass(count++ != 0 ? 'mr-2' : ''));
                        this.contentHeaderBtnCount++;
                    }
                }
                if (this.isCheck) {
                    this.undoSelect = $('<div class="iconBtn translate float-right" translateFor="text.undoSelect" translateTo="popoverTitle"><i class="ti ti-back-left"></i></div>').on('click', () => this.undoAllCheckedRow()).addClass(count++ != 0 ? 'mr-2' : '').hide();
                    rightBtns.append(this.undoSelect);
                }
                this.contentHeader.append(rightBtns)
            }
            this.contentHeaderBtnCount > 0 && this.contentHeader.show();
            createTitleWithIconBtn(this.contentHeader);
        }
    }

    createContentBody() {
        this.widget.append(this.widgetBody.append($('<div class="table-responsive"></div>').append(this.table.append(this.thead).append(this.tbody))));
        this.createTableHeader();
        this.createSearchTable(false, false, false);
    }

    createTableHeader() {
        let theadTr = $('<tr></tr>');
        this.thead.append(theadTr);
        for (let i = 0, l = this.columns.length; i < l; i++) {
            let column = this.columns[i], th = $('<th><span class="translate" translateFor="' + (column.type == 'action' ? 'label.actions' : this.getValue(column.label)) + '"></span></th>');
            i == 0 && th.css('border-left', '0');
            i == l - 1 && th.css('border-right', '0');
            column.width && th.css('min-width', column.width);
            column.minWidth && th.css('min-width', column.minWidth);
            column.maxWidth && th.css('min-width', column.maxWidth);
            column.filter ? th.append($('<i class="la la-filter filter"></i>')) : th.css('text-align', 'center');
            theadTr.append(th);
        }
        if (this.isCheck) {
            let checkAllId = generateID('check-all');
            let that = this;
            this.checkAll = $('<input type="checkbox" name="check-all" id="' + checkAllId + '">').on('change', function () {
                that.node.find('input:checkbox[name="checkbox_item"]').prop('checked', $(this).prop("checked") == false);
                that.node.find('label.click').click();
            });
            theadTr.prepend($('<th style="width:3.2rem;border:0"></th>').append($('<div class="styled-checkbox ml-1"></div>').append(this.checkAll).append($('<label for="' + checkAllId + '"></label>'))));
        }
        translate(theadTr);
    }

    createSearchTable(isRefresh, refreshInterval, isNoty) {
        let that = this;
        if (this.isCheck && !this.primaryKey) {
            alert("请设置primaryKey参数！");
            return;
        }
        if (refreshInterval !== false) {
            this.refreshInterval = refreshInterval;
        } else if (isRefresh === true) {
            this.modalId ? clearModalTimeout(this.modalId, () => refreshInterval = this.refreshInterval) : clearPageTimeout(() => refreshInterval = this.refreshInterval);
        }
        axiosPost({
            url: this.url,
            success: (data) => {
                let list = data.list;
                let notOrderColumns = [], columnIndex = 0, listSize = list.length, colLength = this.columns.length;
                this.isCheck && notOrderColumns.push(columnIndex++);
                for (let a = 0; a < colLength; a++) {
                    this.columns[a].order !== true && notOrderColumns.push(columnIndex);
                    columnIndex++;
                }
                if (isRefresh === true) {
                    this.tbody.find('a').unbind('mouseenter').unbind('mouseleave').each(function () {
                        hidePopoverByNode($(this))
                    });
                    this.saveOldParamAndDestroyDataTable();
                }
                this.tbody.empty();
                for (let i = 0; i < listSize; i++) {
                    let listItem = list[i];
                    let columnTr = $('<tr></tr>').data('data', listItem);
                    this.primaryKey && columnTr.data('primaryKey', listItem[this.primaryKey]);
                    for (let j = 0; j < colLength; j++) {
                        let column = this.columns[j];
                        let columnTd = $('<td></td>');
                        let columnSpan;
                        if (column.type === 'action') {
                            columnTd.css('text-align', 'center').addClass('td-actions');
                            if (column.btns) {
                                for (let k = 0, btnCount = column.btns.length; k < btnCount; k++) {
                                    let columnBtn = column.btns[k];
                                    let btn = $('<a href="javascript:void(0)" class="translate" translateFor="' + this.getValue(columnBtn.translateFor, data) + '" translateTo="popoverTitle"><i class="' + this.getValue(columnBtn.icon, data) + '"></i></a>');
                                    btn.on('click', (event) => {
                                        event.preventDefault();
                                        event.stopPropagation();
                                        if (columnBtn.fun) {
                                            columnBtn.arg ? columnBtn.fun.call(this, columnBtn.arg) : columnBtn.fun.call(this);
                                        } else {
                                            let fun = this[columnBtn.action];
                                            if (typeof fun === 'function') {
                                                fun.call(this, data, columnTr);
                                            }
                                        }
                                    });
                                    createTitle(btn, {
                                        bodyStyle: 'height:2.857rem', bodyContent(){
                                            return btn.attr('popoverTitle')
                                        }, leftOffset: '-0.071rem'
                                    });
                                    columnTd.append(btn);
                                }
                            }
                        } else if (column.value) {
                            columnTd.append(typeof column.value == 'function' ? column.value(listItem, columnTr, this) : column.value);
                        } else if (column.code) {
                            let columnValue = (listItem[column.code] !== undefined && listItem[column.code] !== null) ? listItem[column.code] : column.defaultValue !== undefined ? column.defaultValue : '';
                            if (column.switch) {
                                if (i == 0) {
                                    this.switchConditionCode = column.conditionCode || this.primaryKey;
                                    this.switchConfirmTitleReplace = column.confirmTitleReplace || this.confirmTitleReplace;
                                    this.switchConfirmCloseContent = column.confirmCloseContent;
                                    this.switchConfirmOpenContent = column.confirmOpenContent;
                                    this.switchShowCode = column.showCode || this.showCode;
                                    this.switchChangeUrl = column.changeUrl;
                                    this.allSwitchChangeUrl = column.allChangeUrl;
                                }
                                columnSpan = $('<button type="button" class="switch switch-style-2 ' + (columnValue == 'O' ? 'switch-checked' : 'switch-checked-Unselected') + '"><span class="switch-inner translate lang" translateFor="switch" translateValue="' + columnValue + '"></span></button>').on('click', function () {
                                    let switchTo = listItem.taskSwitch == 'O' ? 'C' : 'O';
                                    that.changeSwitch({
                                        switchBtnArray: [$(this)],
                                        url: that.switchChangeUrl + '/' + listItem[that.switchConditionCode] + "/" + switchTo,
                                        switchTo: switchTo,
                                        confirmTitleReplace: [cdata(listItem[that.switchShowCode])]
                                    });
                                }).data('switch', columnValue);
                            } else if (column.translateFor) {
                                columnSpan = $('<span class="translate" translateFor="' + column.translateFor + '" translateValue="' + columnValue + '"></span>');
                            } else {
                                columnSpan = $('<span>' + columnValue + '</span>');
                            }
                            columnTd.append(columnSpan);
                        } else {
                            alert('columns[' + j + ']未配置code!');
                            return;
                        }
                        column.textEllipsis === true && columnSpan && columnSpan.addClass('text-ellipsis');
                        column.primary === true && columnTd.addClass('text-primary');
                        column.selector === true && columnTd.addClass('selector');
                        column.align && columnTd.css('text-align', column.align);
                        column.addClass && columnSpan.addClass(column.addClass);
                        column.addClassFun && columnSpan.addClass(column.addClassFun(listItem));
                        columnTr.append(columnTd);
                    }
                    this.tbody.append(columnTr);
                }
                removeTextEllipsis(this.tbody);
                if (!this.isDataTable) {
                    if (listSize > 0) {
                        translate(this.tbody);
                    } else {
                        let emptyDiv = $("<div style='padding:.85rem;text-align:center'><span class='translate' translateFor='message.resultIsEmpty'></span></div>");
                        this.tbody.parent().after(emptyDiv);
                        translate(emptyDiv);
                    }
                } else {
                    this.createSearchTableBody({
                        ordering: true,
                        columnDefs: [{'orderable': false, 'targets': notOrderColumns}]
                    });
                }
                textEllipsis(this.tbody, false);
                if (isRefresh === true) {
                    this.loadOldParamDataTable();
                    if (isNoty !== false) {
                        new Noty({
                            type: 'success',
                            layout: 'bottomRight',
                            text: '<span class="translate" translateFor="message.singleRefreshSuccess"></span>',
                            progressBar: true,
                            timeout: 1500,
                            animation: {open: 'animated bounceInRight', close: 'animated bounceOutRight'}
                        }).show();
                    }
                    if (refreshInterval !== undefined && refreshInterval != false) {
                        this.modalId ? setModalTimeout(this.modalId, () => this.createSearchTable(isRefresh, refreshInterval, false), refreshInterval) : setPageTimeout(() => this.createSearchTable(isRefresh, refreshInterval, false), refreshInterval);
                    }
                } else {
                    getPageData() && this.dataTable && this.dataTable.search(getPageData()).draw(false);
                }
            }
        });
    }

    createSearchTableBody(options) {
        let that = this;
        let checkedRowLength = this.checkedRows.length;
        this.tbody.find('tr').each(function () {
            let row = $(this);
            let primaryKey = row.data('primaryKey');
            if (row.find('input[name="checkbox_item"]').length == 0) {
                let id = generateID();
                let checkboxItem = $('<input type="checkbox" name="checkbox_item" id="checkbox-' + id + '">').on('change', function () {
                    $(this).prop('checked') == true ? that.pushCheckedRow(row.addClass('selected')) : that.undoCheckedRow(row.removeClass('selected'));
                    that.judgeCheckedRows();
                    let curPageSelectedCount = that.tbody.find('tr.selected').length;
                    if (curPageSelectedCount == 0) {
                        that.checkAll.prop('checked', false);
                    } else {
                        curPageSelectedCount == that.tbody.find('tr').length && that.checkAll.prop('checked', true);
                    }
                });
                row.prepend($('<td class="selector"></td>').append($('<div class="styled-checkbox ml-1"></div>').append(checkboxItem).append($('<label class="click" for="checkbox-' + id + '"></label>'))));
            }
            for (let i = 0; i < checkedRowLength; i++) {
                let checkedRow = that.checkedRows[i];
                if (primaryKey == checkedRow.primaryKey) {
                    checkedRow.row = row;
                    row.find('label.click').click();
                }
            }
        });
        translate(this.tbody);
        this.bindSelector();
        let dataTableParams = {
            lengthMenu: [
                [10, 15, 20, -1],
                [10, 15, 20, "All"]
            ],
            order: [1, 'asc'],
            ordering: false,
            bProcessing: true,
            bAutoWidth: false,
            initComplete(){
                this.api().columns().every(function () {
                    let column = this;
                    let columnTh = $(column.header());
                    let filter = columnTh.find('.filter');
                    if (filter && filter.length > 0) {
                        let filterValue = filter.attr('filterValue') || '';
                        if (filterValue != '') {
                            let searchValue = getSearchValue(filterValue);
                            column.search(searchValue != '' ? '^' + searchValue + '$' : '', true, false).draw();
                        }
                        filter.off('click').on('click', function () {
                            let $this = $(this);
                            if ($this.hasClass('filter-menu-show')) {
                                hidePopoverByNode($this);
                                return;
                            }
                            $this.addClass('filter-menu-show');
                            let filterArray = [];
                            let filterValue = $this.attr('filterValue');
                            if (filterValue != undefined && filterValue != '') {
                                filterArray = filterValue.split(splitWords);
                            }
                            let popoverBodyContent = $('<div></div>');
                            column.data().unique().sort().each(function (d) {
                                let $span = $(d);
                                if ($span[0].nodeName != 'SPAN') {
                                    $span = $span.find('span');
                                }
                                let translateFor = getTranslateFor($span);
                                let li = $('<li></li>');
                                li.append($('<a href="javascript:void(0);" style="width:100%;padding:.5rem 1rem"><span class="filter-check-mark ' + ($.inArray(translateFor, filterArray) != -1 ? 'active' : '') + '"></span><span style="display:inline-block">' + getTranslateValueByFor(translateFor) + '</span></a>').on('click', function (e) {
                                    e.preventDefault();
                                    $this = $(this);
                                    let filterValue = filter.attr('filterValue') || '';
                                    let filterCount = parseInt(filter.attr('filterCount') || '0');
                                    let checkMark = $this.find('.filter-check-mark');
                                    if (checkMark.hasClass('active')) {
                                        if (filterValue.includes(splitWords + translateFor)) {
                                            filterValue = filterValue.replace(splitWords + translateFor, '');
                                        } else if (filterValue.includes(translateFor + splitWords)) {
                                            filterValue = filterValue.replace(translateFor + splitWords, '');
                                        } else {
                                            filterValue = filterValue.replace(translateFor, '');
                                        }
                                        filterCount--;
                                        checkMark.removeClass('active');
                                    } else {
                                        if (filterValue != '') {
                                            filterValue = filterValue + splitWords + translateFor;
                                        } else {
                                            filterValue = translateFor;
                                        }
                                        filterCount++;
                                        checkMark.addClass('active');
                                    }
                                    if (filterCount != 0) {
                                        filter.removeClass('active').addClass('active');
                                    } else {
                                        filter.removeClass('active');
                                    }
                                    filter.attr('filterValue', filterValue);
                                    filter.attr('filterCount', filterCount + '');
                                    let searchValue = getSearchValue(filterValue);
                                    column.search(searchValue != '' ? '^' + searchValue + '$' : '', true, false).draw();
                                    adjustPopoverPositionByNode(filter);
                                }));
                                popoverBodyContent.append(li);
                            });
                            showPopover($this, {
                                direction: 'bottom',
                                bodyStyle: 'width:12.5rem;max-height:25rem;overflow-y:auto',
                                bodyContent: popoverBodyContent,
                                animate: 'slide',
                                animateTime: 300,
                                niceScroll: true,
                                scrollLock: true,
                                hideFun(){
                                    filter.removeClass('filter-menu-show');
                                }
                            });
                        });
                    }
                });
            },
            drawCallback(){
                if (that.dataTable) {
                    let selectedTrs = that.tbody.find('tr.selected');
                    if (selectedTrs.length != 0) {
                        let checkedRowLength = that.checkedRows.length;
                        if (checkedRowLength == 0) {
                            selectedTrs.find('label.click').click();
                        } else {
                            selectedTrs.each(function () {
                                let selectedTr = $(this), isChecked = false;
                                for (let i = 0; i < checkedRowLength; i++) {
                                    if (selectedTr.data('primaryKey') == that.checkedRows[i].primaryKey) {
                                        isChecked = true;
                                        break;
                                    }
                                }
                                !isChecked && selectedTr.find('label.click').click();
                            });
                        }
                    }
                    that.checkAll.prop('checked', selectedTrs.length == that.tbody.find('tr').length);
                    resizeContentWithNiceScroll(true);
                    textEllipsis();
                    that.dataTableNiceScroll();
                }
            }
        };
        if (options) {
            for (let key in options) {
                if (options.hasOwnProperty(key)) {
                    dataTableParams[key] = options[key];
                }
            }
        }
        lang == 'zh' && (dataTableParams['language'] = getTranslateValueByFor('dataTable.language'));
        this.dataTable = this.tbody.parent().DataTable(dataTableParams);
        this.tableContainer = $(this.dataTable.table().node()).parent();
        this.dataTableContainer = $(this.dataTable.table().container());
        beautifySelect(this.dataTableContainer);
        textEllipsis();
        this.dataTableNiceScroll();
    }

    bindSelector() {
        this.tbody.find('.selector').off('mousedown').on('mousedown', function (event) {
            let mousedownTarget = $(event.target);
            let mousedownTr = $(event.target).parents('tr');
            let selectorTable = $(this).parents('table');
            let grabbingTimeoutId = -1;
            let grabTimeoutId = setTimeout(function () {
                selectorTable.addClass('grab');
                grabbingTimeoutId = setTimeout(function () {
                    selectorTable.removeClass('grab').addClass('grabbing');
                    let tableContainer = selectorTable.parent();
                    let scrollLeft = tableContainer.scrollLeft();
                    let left = event.clientX;
                    $(document).on('mousemove', function (event) {
                        tableContainer.scrollLeft(scrollLeft - event.clientX + left);
                    });
                }, 150)
            }, 500);
            $(document).on('mouseup', function (event) {
                $(document).off('mousemove').off('mouseup');
                clearTimeout(grabTimeoutId);
                grabbingTimeoutId != -1 && clearTimeout(grabbingTimeoutId);
                if (selectorTable.hasClass('grab') || selectorTable.hasClass('grabbing')) {
                    selectorTable.removeClass('grab grabbing');
                    return;
                }
                let mouseupTarget = $(event.target);
                let mouseupTr = $(event.target).parents('tr');
                if (mousedownTarget.hasClass('click') && mouseupTarget.hasClass('click')) {
                    return;
                }
                if (mousedownTr[0] == mouseupTr[0]) {
                    mouseupTr.find('label.click').click();
                }
            });
        });
    }

    pushCheckedRow(row) {
        let primaryKey = row.data('primaryKey'), isChecked = false;
        for (let i = 0, l = this.checkedRows.length; i < l; i++) {
            if (this.checkedRows[i].primaryKey == primaryKey) {
                isChecked = true;
                break;
            }
        }
        !isChecked && this.checkedRows.push({primaryKey: primaryKey, row: row});
    }

    removeCheckedRows(checkedRowArray) {
        if ($.isArray(checkedRowArray)) {
            $.each(checkedRowArray, (i, item) => {
                this.dataTable.rows(item).remove();
                this.undoCheckedRow(item);
            });
        } else {
            this.dataTable.rows(checkedRowArray).remove();
            this.undoCheckedRow(checkedRowArray);
        }
        this.dataTable.draw(false);
        this.judgeCheckedRows();
    }

    eachCheckedRows(fun) {
        $.each(this.checkedRows, function (i, item) {
            item.row.length > 0 && fun(item.row.data('data'), item.row);
        });
    }

    undoCheckedRow(row) {
        let primaryKey = row.data('primaryKey');
        for (let i = 0, l = this.checkedRows.length; i < l; i++) {
            if (this.checkedRows[i].primaryKey == primaryKey) {
                this.checkedRows.splice(i, 1);
                break;
            }
        }
    }

    undoAllCheckedRow() {
        if (this.checkedRows.length > 0) {
            this.tbody.find('tr.selected').find('label.click').click();
            this.contentHeaderBtnCount == 0 && this.contentHeader && this.contentHeader.hide();
            this.batchBtnContainer && this.batchBtnContainer.hide();
            this.undoSelect && this.undoSelect.hide();
            this.checkedRows = [];
        }
    }

    judgeCheckedRows() {
        if (this.checkedRows.length > 0) {
            this.contentHeaderBtnCount == 0 && this.contentHeader && this.contentHeader.show();
            this.batchBtnContainer && this.batchBtnContainer.show();
            this.undoSelect && this.undoSelect.show();
        } else {
            this.contentHeaderBtnCount == 0 && this.contentHeader && this.contentHeader.hide();
            this.batchBtnContainer && this.batchBtnContainer.hide();
            this.undoSelect && this.undoSelect.hide();
        }
    }

    getDataTable() {
        return this.dataTable;
    }

    saveOldParamAndDestroyDataTable() {
        if (this.dataTable && this.tableContainer) {
            this.oldPage = this.dataTable.page();
            this.searchValue = this.dataTable.search();
            this.pageLength = this.dataTable.page.len();
            this.scrollLeft = this.tableContainer.scrollLeft();
            this.tableContainer.getNiceScroll().remove();
            this.dataTable.destroy();
        }
    }

    loadOldParamDataTable() {
        if (this.dataTable && this.tableContainer) {
            this.dataTable.search(this.searchValue).page(this.oldPage).page.len(this.pageLength).draw(false);
            this.tableContainer.scrollLeft(this.scrollLeft);
        }
    }

    dataTableNiceScroll() {
        let niceScrollWidth = 0.36;
        if (this.dataTable && this.tableContainer) {
            let niceScroll = this.tableContainer.getNiceScroll();
            if (niceScroll.length != 0) {
                niceScroll.resize();
            } else {
                let dataTableContainerParent = this.tableContainer.parent();
                let dataTableContainerParentPrev = dataTableContainerParent.prev();
                debugger;
                let railhTop = [this.tableContainer[0], dataTableContainerParent.css('margin-top'), dataTableContainerParentPrev[0], dataTableContainerParentPrev.css('margin-top'),
                    this.widgetBody.css('padding-top'), this.widget.css('padding-top'), $('#content').css('padding-top'), '-2px', '-' + niceScrollWidth + 'rem'];
                let widgetHeader = $('.widget-header');
                if (widgetHeader.length > 0) {
                    railhTop.push(widgetHeader[0]);
                }
                if (this.contentHeader && this.contentHeader.length > 0) {
                    railhTop.push(this.contentHeader[0]);
                    railhTop.push(this.contentHeader.css('margin-top'));
                }
                this.tableContainer.niceScroll({
                    railpadding: {
                        top: 0,
                        right: -2,
                        left: 0,
                        bottom: 0
                    },
                    scrollspeed: 60,
                    zindex: 1,
                    cursorborderradius: niceScrollWidth + "rem",
                    cursorwidth: niceScrollWidth + "rem",
                    cursorcolor: "rgba(52, 40, 104, 0.2)",
                    cursorborder: "rgba(52, 40, 104, 0.2)",
                    oneaxismousemode: false,
                    railhTop: railhTop
                });
            }
        }
    }

    changeSwitch(options) {
        let confirmParams = {
            title: options.isAll ? "confirm.title.commonAllAction" : "confirm.title.commonAction",
            okFun(){
                $.each(options.switchBtnArray, function (i, item) {
                    item = item instanceof jQuery ? item : $(item);
                    item.addClass('switch-loading');
                });
                axiosPost({
                    url: options.url,
                    success: () => this.refresh(),
                    error(){
                        $.each(options.switchBtnArray, function (i, item) {
                            item = item instanceof jQuery ? item : $(item);
                            item.removeClass('switch-loading');
                        });
                    }
                });
            }
        };
        let titleReplace;
        if (options.switchTo == 'C') {
            titleReplace = ['confirm.label.close'];
            confirmParams['content'] = this.switchConfirmCloseContent;
        } else {
            titleReplace = ['confirm.label.open'];
            confirmParams['content'] = this.switchConfirmOpenContent;
        }
        titleReplace = this.switchConfirmTitleReplace ? titleReplace.concat(this.switchConfirmTitleReplace) : titleReplace;
        titleReplace = options.confirmTitleReplace ? titleReplace.concat(options.confirmTitleReplace) : titleReplace;
        confirmParams['titleReplace'] = titleReplace;
        newConfirmModal(confirmParams);
    }

    batchChangeSwitch(isOpen) {
        let checkedTaskIdStr = '', checkedIdStr = '', switchBtnArray = [], switchTo = isOpen ? 'O' : 'C';
        this.eachCheckedRows((data, row) => {
            let switchBtn = row.find('button.switch');
            if (switchBtn.data('switch') != switchTo) {
                checkedIdStr = checkedIdStr + data[this.switchConditionCode] + ',';
                checkedTaskIdStr = checkedTaskIdStr + data[this.switchShowCode] + ', ';
                switchBtnArray.push(switchBtn);
            }
        });
        if (checkedIdStr == '') {
            showErrorNoty({
                translateFor: "message.noSelected" + switchTo,
                translateReplace: this.switchConfirmTitleReplace
            });
            return;
        }
        checkedIdStr = checkedIdStr.substr(0, checkedIdStr.length - 1);
        checkedTaskIdStr = checkedTaskIdStr.substr(0, checkedTaskIdStr.length - 2);
        this.changeSwitch({
            switchBtnArray: switchBtnArray,
            url: this.switchChangeUrl + '/' + checkedIdStr + "/" + switchTo,
            switchTo: switchTo,
            confirmTitleReplace: [cdata(checkedTaskIdStr)]
        });
    }

    changeAllSwitch(isOpen) {
        let switchTo = isOpen ? 'O' : 'C';
        this.changeSwitch({
            switchBtnArray: this.tbody.find('button.switch'),
            url: this.allSwitchChangeUrl + '/' + switchTo,
            switchTo: switchTo,
            isAll: true
        });
    }

    singleDelete(data, row) {
        if (!this.delete.conditionCode || !this.delete.url || !this.delete.showCode) {
            alert('未配置delete参数！');
            return;
        }
        if (!this.delete.condition(data)) {
            showErrorNoty({translateFor: "message.disallowedDeleteTask"});
            return;
        }
        newConfirmModal({
            title: "confirm.title.commonAction",
            titleReplace: ["confirm.label.delete", cdata(data[this.delete.showCode])],
            content: this.delete.confirmContent,
            okFun: () => {
                axiosPost({
                    url: this.delete.url + '/' + data[this.delete.conditionCode],
                    success(dataMsg) {
                        setTimeout(function () {
                            if (dataMsg.status === 'success') {
                                showSuccessNoty({translateFor: dataMsg.msgCode});
                            } else {
                                showErrorNoty({translateFor: dataMsg.msgCode});
                            }
                            if (dataMsg.status == 'success') {
                                this.removeCheckedRows(row);
                            }
                        }, 500);
                    }
                });
            }
        });
    }

    batchDelete() {

    }

    refresh() {
        this.createSearchTable(true, false, false)
    }

    refreshDataTable() {
        if (this.dataTable) {
            let oldPage = this.dataTable.page();
            let searchValue = this.dataTable.search();
            let pageLength = this.dataTable.page.len();
            this.dataTable.destroy();
            translate(this.dataTable);
            this.createSearchTableBody();
            this.dataTable.search(searchValue).page(oldPage).page.len(pageLength).draw(false);
            textEllipsis();
            this.dataTableNiceScroll();
        }
    }

    getValue(expression, data) {
        if (expression == undefined || expression == null) {
            return '';
        }
        if (typeof expression === 'function') {
            return expression.call(this, data);
        }
        return expression;
    }
}

(function ($) {
    $.fn.SearchPage = function (options) {
        let searchPage = new SearchPage($(this), options);
        let searchPageArray = getPageContext('searchPages');
        if (!searchPageArray) {
            searchPageArray = [];
            pushPageContext('searchPages', searchPageArray);
        }
        searchPageArray.push(searchPage);
        return searchPage;
    };
})(jQuery);